/**
 * Calculator Tool
 * 
 * A simple calculator tool that can perform basic arithmetic operations
 */

import { z } from 'zod';
import type { ToolDefinition } from '@/types';
import { createTextResult, createErrorResult } from '../tool-factory';

/**
 * Calculator tool definition
 */
export const calculatorTool: ToolDefinition = {
  name: 'calculator',
  description: 'Perform basic arithmetic calculations. Supports addition, subtraction, multiplication, division, and exponentiation.',
  inputSchema: z.object({
    expression: z.string().describe('Mathematical expression to evaluate (e.g., "2 + 2", "10 * 5", "2 ** 3")'),
  }),
  handler: async (args) => {
    try {
      const { expression } = args;
      
      // Sanitize the expression to prevent code injection
      const sanitized = expression.replace(/[^0-9+\-*/().\s]/g, '');
      
      if (sanitized !== expression) {
        return createErrorResult('Invalid characters in expression. Only numbers and operators (+, -, *, /, **) are allowed.');
      }
      
      // Evaluate the expression
      // Note: Using Function constructor is safer than eval() but still requires caution
      const result = new Function(`return ${sanitized}`)();
      
      if (typeof result !== 'number' || !isFinite(result)) {
        return createErrorResult('Invalid calculation result');
      }
      
      return createTextResult(`Result: ${result}`);
    } catch (error) {
      return createErrorResult(error as Error);
    }
  },
};

/**
 * Advanced calculator tool with more functions
 */
export const advancedCalculatorTool: ToolDefinition = {
  name: 'advanced_calculator',
  description: 'Perform advanced mathematical calculations including trigonometry, logarithms, and more.',
  inputSchema: z.object({
    operation: z.enum(['sin', 'cos', 'tan', 'sqrt', 'log', 'ln', 'abs', 'round', 'ceil', 'floor']).describe('Mathematical operation to perform'),
    value: z.number().describe('Input value for the operation'),
  }),
  handler: async (args) => {
    try {
      const { operation, value } = args;
      
      let result: number;
      
      switch (operation) {
        case 'sin':
          result = Math.sin(value);
          break;
        case 'cos':
          result = Math.cos(value);
          break;
        case 'tan':
          result = Math.tan(value);
          break;
        case 'sqrt':
          result = Math.sqrt(value);
          break;
        case 'log':
          result = Math.log10(value);
          break;
        case 'ln':
          result = Math.log(value);
          break;
        case 'abs':
          result = Math.abs(value);
          break;
        case 'round':
          result = Math.round(value);
          break;
        case 'ceil':
          result = Math.ceil(value);
          break;
        case 'floor':
          result = Math.floor(value);
          break;
        default:
          return createErrorResult(`Unknown operation: ${operation}`);
      }
      
      if (!isFinite(result)) {
        return createErrorResult('Invalid calculation result');
      }
      
      return createTextResult(`${operation}(${value}) = ${result}`);
    } catch (error) {
      return createErrorResult(error as Error);
    }
  },
};

